package vue;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import utiles.K;

import metier.Carte;
import metier.Element;
import metier.Herbe;
import metier.Nouriturre;
import metier.Position;
import metier.Roche;

import controleur.ControllerCreationCarte;

public class VueModificationCarte extends FourmizFrame implements
        ActionListener, MouseListener, ListSelectionListener {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    protected JButton btn_modifier;
    protected String[] elements = {"Herbe", "Roche", "Nourriture"};
    protected String choixElement = null;
    protected HashMap<JLabel, Integer> gridLabel = new HashMap<JLabel, Integer>();
    protected ControllerCreationCarte cont;
    protected boolean isMousePressed = false;
    protected JLabel labelParam;
    protected JTextField fieldParam;
    protected Carte carte;

    public VueModificationCarte(ControllerCreationCarte c, Carte carte) {
        this.carte = carte;
        this.setTitle("Modification de la carte");
        this.setSize(800, 600);
        this.setLocationRelativeTo(null);
        this.setLayout(new BorderLayout());

        // on construit la grille de la carte
        this.cont = c;
        Border border = BorderFactory.createLineBorder(Color.DARK_GRAY);
        GridLayout gridLayout = new GridLayout(this.carte.getLongueur(),
                this.carte.getLargeur());
        JPanel grid = new JPanel();
        grid.setLayout(gridLayout);
        for (int y = 0; y < carte.getLongueur(); y++) {
            for (int x = 0; x < carte.getLargeur(); x++) {
                ArrayList<Element> elements = this.carte.getElements(new Position(x, y));

                if (elements.size() > 0) {
                    JLabel label = new JLabel("");
                    label.setOpaque(true);
                    label.addMouseListener(this);
                    label.setBorder(border);

                    Element element = elements.get(0);
                    label.setBackground(element.getCouleur());
                    grid.add(label);
                    this.gridLabel.put(label, 0);
                }
            }
        }

        // on dresse la liste des éléments positionnables sur la carte
        JPanel menuDroit = new JPanel();
        BoxLayout boxLayout = new BoxLayout(menuDroit, BoxLayout.Y_AXIS);
        menuDroit.setLayout(boxLayout);
        JLabel lbl_titre = new JLabel("Eléments");
        lbl_titre.setAlignmentX(Component.CENTER_ALIGNMENT);
        menuDroit.add(lbl_titre);
        menuDroit.add(Box.createVerticalStrut(20));

        JList<String> listeElements = new JList<String>(this.elements);
        listeElements.setFixedCellWidth(150);
        listeElements.setFixedCellHeight(30);
        listeElements.addListSelectionListener(this);
        menuDroit.add(listeElements);
        menuDroit.add(Box.createVerticalStrut(20));

        // paramètre
        this.labelParam = new JLabel("Paramètre : ");
        this.fieldParam = new JTextField("0");
        this.fieldParam.setPreferredSize(new Dimension(40, 20));
        JPanel panelParam = new JPanel();
        panelParam.add(labelParam);
        panelParam.add(fieldParam);
        menuDroit.add(panelParam);

        // bouton de création de la map
        this.btn_modifier = new JButton("Modifier");
        this.btn_modifier.setAlignmentX(Component.CENTER_ALIGNMENT);
        this.btn_modifier.addActionListener(this);
        menuDroit.add(this.btn_modifier);

        this.add("Center", grid);
        this.add("East", menuDroit);

        this.setVisible(true);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    protected void sauvegarder(String nomCarte) {
        if (cont.createDocument(nomCarte, this.carte)) {
            this.cont.notifyMapCreated(this.carte);
            JOptionPane.showMessageDialog(this, "Carte sauvegardée");
        } else {
            JOptionPane.showMessageDialog(this, "Erreur lors de la sauvegarde");
        }
    }

    private void placeElement(JLabel label) {
        Color couleur = null;
        Integer difficulte = Integer.parseInt(this.fieldParam.getText());
        Element element = null;
        switch (this.choixElement) {
            case "Herbe":
                element = new Herbe(1, 1, difficulte);
                couleur = Color.GREEN;
                break;
            case "Roche":
                element = new Roche(1, 1, difficulte);
                couleur = Color.GRAY;
                break;
            case "Nourriture":
                element = new Nouriturre(1, 1, difficulte);
                couleur = Color.YELLOW;
                break;
        }

        if (element == null) {
            return;
        }

        int posx = label.getX() / label.getWidth();
        int posy = label.getY() / label.getHeight();
        Position position = new Position(posx, posy);

        // on supprime tous les éléments de la case
        this.carte.removeElements(position);
        this.carte.addElement(element, position);

        label.setOpaque(true);
        label.setBackground(couleur);
        this.gridLabel.put(label, Integer.parseInt(this.fieldParam.getText()));
    }

    @Override
    public void valueChanged(ListSelectionEvent listSelectionEvent) {
        boolean adjust = listSelectionEvent.getValueIsAdjusting();
        if (!adjust) {
            JList list = (JList) listSelectionEvent.getSource();
            int selections[] = list.getSelectedIndices();
            Object selectionValues[] = list.getSelectedValues();
            for (int i = 0, n = selections.length; i < n; i++) {
                this.choixElement = (String) selectionValues[i];
            }
            if (this.choixElement != null) {
                if (this.choixElement.equals("Nourriture")) {
                    this.labelParam.setText("Quantité : ");
                } else {
                    this.labelParam.setText("Difficulté : ");
                }

                String val = "0";
                switch (this.choixElement) {
                    case "Herbe":
                        val = "0";
                        break;
                    case "Nourriture":
                        val = "100";
                        break;
                    case "Roche":
                        val = "2000";
                        break;

                }

                this.fieldParam.setText(val);
            }
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
    }

    @Override
    public void mousePressed(MouseEvent e) {
        if (this.choixElement != null) {
            this.isMousePressed = true;

            JLabel source = (JLabel) e.getSource();

            this.placeElement(source);
        }
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        this.isMousePressed = false;
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        if (this.isMousePressed) {
            this.placeElement((JLabel) e.getSource());
        }
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String nomCarte = JOptionPane.showInputDialog("Nom de la carte :");
        if (nomCarte != null) {
            this.sauvegarder(nomCarte);
        }
    }
}
